package com.walter.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.walter.common.PageVO;
import com.walter.consts.DictConst;
import com.walter.entity.Param;
import com.walter.entity.User;
import com.walter.exception.LogicException;
import com.walter.mapper.ParamMapper;
import com.walter.mapper.UserMapper;
import com.walter.model.form.UpdateParamForm;
import com.walter.model.query.ParamQuery;
import com.walter.security.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

/**
 * @author ：ch
 * @date ：Created in 2021/5/25
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class ParamService {
    @Autowired
    private ParamMapper paramMapper;

    @Autowired
    private UserMapper userMapper;


    // find
    public PageVO<Param> find(ParamQuery query){
        return Optional.of(query)
                .map(q -> new Page(q.getPage().getPageNum(),q.getPage().getPageSize()))
                .map(p -> new PageVO(p.setRecords(paramMapper.find(p,BeanUtil.beanToMap(query)))))
                .get();
    }

    // findOne
    public Param findOne(String key){
        if (StrUtil.isEmpty(key)){
            log.info("key is null or ''");
            throw new LogicException("key为空");
        }
        Param param = paramMapper.findById(key);
        if (null == param){
            log.info("param is null");
            throw new LogicException("key为" + key + "的系统参数不存在");
        }
        return param;
    }

    // update is_need value
    @Transactional
    public Integer updateParam(UpdateParamForm form){
        // 暂时只有内置超管 admin 可以维护系统设置参数 todo
        Integer operator = (Integer) Jwt.currentId();
        User admin = userMapper.selectById(operator);
        if (!admin.getUserName().equals("admin")) { //hardCode
            log.info("only admin can set system params");
            throw new LogicException("您没有权限进行系统设置");
        }
        Param existParam = this.findOne(form.getKey()).setUpdateTime(new Date());
        // 判断value是否要填
        if (existParam.getIsNeed().equals(DictConst.YES)
                && StrUtil.isEmpty(form.getValue())){
            log.info("param[key={}]'s value can not equal null or ''",form.getKey());
            throw new LogicException("key为" + form.getKey() + "的系统参数的值不能为空");
        }
        BeanUtil.copyProperties(form,existParam);
        return paramMapper.updByParams(existParam);
    }

}
